using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core.Data;
using Nop.Plugin.Misc.DynamicsCrm.Data;

namespace Nop.Plugin.Misc.DynamicsCrm.Services
{
    public class DynamicsCrmEventQueueingService : IDynamicsCrmEventQueueingService
    {
        private const string QUEUE_ALL_CONTACTS = "INSERT INTO DynamicsCrmEventQueue (EntityType, EntityId, EventType, CreatedOnUtc) SELECT 'CONTACT', Id, 'I', CreatedOnUtc FROM dbo.Customer WHERE Not(Email IS NULL AND BillingAddress_Id IS NULL) ORDER By CreatedOnUtc";
        private const string QUEUE_ALL_NEWSLETTERSUBS = "INSERT INTO DynamicsCrmEventQueue (EntityType, EntityId, EventType, CreatedOnUtc) SELECT 'NEWSLETTERSUBS', Id, 'I', CreatedOnUtc FROM dbo.NewsLetterSubscription WHERE Active = 1 AND Email not in (SELECT Email FROM dbo.Customer where Email is not null) ORDER By CreatedOnUtc";
        private const string QUEUE_ALL_ORDERS = "INSERT INTO DynamicsCrmEventQueue (EntityType, EntityId, EventType, CreatedOnUtc) SELECT 'SALESORDER', Id, 'I', CreatedOnUtc FROM dbo.[Order] ORDER By CreatedOnUtc";

        private readonly IRepository<DynamicsCrmEventQueue> _repository;
        private readonly DynamicsCrmObjectContext _context;

        public DynamicsCrmEventQueueingService(IRepository<DynamicsCrmEventQueue> repository, DynamicsCrmObjectContext context)
        {
            _repository = repository;
            _context = context;
        }

        /// <summary>
        /// Deletes the specified record.
        /// </summary>
        /// <param name="record">The record.</param>
        public virtual void Delete(DynamicsCrmEventQueue record)
        {
            if (record == null)
                throw new ArgumentNullException("record");

            _repository.Delete(record);
        }

        /// <summary>
        /// Inserts the specified record.
        /// </summary>
        /// <param name="record">The record.</param>
        public virtual void Insert(DynamicsCrmEventQueue record)
        {
            if (record == null)
                throw new ArgumentNullException("record");

            _repository.Insert(record);
        }
        
        /// <summary>
        /// Queues all contacts.
        /// </summary>
        public virtual void QueueAllContacts()
        {
            //NOTE: While I dislike executing straight SQL from C#, I think straight SQL is the best solution for this particular action.
            // My logic is that #1 this query takes no arguments, it is a batch query and #2 this is potentially a very big operation.
            // Loading all of the NewsLetterSubscriptions, iterating them, converting them, and submitting the changes just seems like we would not be taking advantage of our tools (SQLServer).
            _context.Database.ExecuteSqlCommand(QUEUE_ALL_CONTACTS);
            _context.SaveChanges();
        }

        /// <summary>
        /// Queues all orders.
        /// </summary>
        public virtual void QueueAllOrders()
        {
            _context.Database.ExecuteSqlCommand(QUEUE_ALL_ORDERS);
            _context.SaveChanges();
        }


        /// <summary>
        /// Dequeues the list.
        /// </summary>
        /// <returns></returns>
        public virtual IList<DynamicsCrmEventQueue> GetAll()
        {
            var query = from r in _repository.Table
                        orderby r.CreatedOnUtc ascending 
                        select r;

            return query.Take(1000).ToList();
        }
    }
}